<?php

namespace DuAdmin\Validators;

use Yii;
use yii\validators\Validator;

/**
 * 短信和邮件验证码验证器
 */
class SendCaptchaValidator extends Validator
{
    const MODE_SMS = 'sms';

    const MODE_MAIL = 'mail';

    public $mode = 'sms';

    public $targetField = "mobile";

    public $length = 6;

    public function validateAttribute($model, $attribute)
    {
        if (!isset($model[$this->targetField])) {
            $model->addError($attribute, '没有填写接受验证码的信息');
            return;
        }
        $value = $model->$attribute;
        $targetValue = $model[$this->targetField];
        if (strlen($value) != $this->length) {
            $model->addError($attribute, '验证码格式不正确');
            return;
        }
        $originValue = $this->getOriginValue($targetValue);
        if ($originValue != $value) {
            $model->addError($attribute, '验证码错误' . $originValue . '=' . $value);
            return;
        }
    }

    protected function getOriginValue($targetValue)
    {
        return Yii::$app->cache->get("sys-" . $this->mode . '-captcha:' . $targetValue);
    }

    protected function deleteOriginValue($targetValue)
    {
        Yii::$app->cache->delete("sys-" . $this->mode . '-captcha:' . $targetValue);
    }

    public function clientValidateAttribute($model, $attribute, $view)
    {
        return <<<JS
if(value.length != $this->length) {
    messages.push('验证码格式不正确');
}
JS;
    }
}
